<template>
    <van-address-edit 
        show-delete
        show-set-default
        :area-list="areaList"
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        :address-info="address"
        @save="save"
        @delete="del"
    />
</template>

<script setup>
    //引入地区数据
    import { areaList } from '@vant/area-data'

    const {proxy} = getCurrentInstance()

    let addid = proxy.$route.query.addid ? proxy.$route.query.addid : 0

    let business = proxy.$business.value

    let address = ref({
        // name: '张三',
        // tel: '13512666443',
        // areaCode: '',
    })

    // return false
    //声明周期钩子函数
    onMounted(() => {
        AddressData()
    })

    //数据渲染
    const AddressData = async () =>
    {
        var params = {
            id: addid,
            busid: business.id
        }

        var result = await proxy.$POST({url: 'address/info', params})

        if(result.code == 0)
        {
            proxy.$fail({
                message: result.msg,
                duration: 1000,
                onClose: () => proxy.$router.go(-1)
            })
            return false
        }

        address.value = {
            name: result.data.consignee,
            tel: result.data.mobile,
            areaCode: result.data.district || result.data.city || result.data.province,
            addressDetail: result.data.address,
            isDefault: result.data.status == '1' ? true : false,
        }
    }
    //保存
    const save = async (values) => {

        var params = {
            id: addid,
            busid: business.id,
            consignee: values.name,
            address: values.addressDetail,
            mobile: values.tel,
            status: values.isDefault ? 1 : 0,
            code: values.areaCode
        }

        var result = await proxy.$POST({url: 'address/edit', params})

        if(result.code == 0)
        {
            proxy.$fail(result.msg)
            return false
        }

        proxy.$success({
            message:result.msg,
            duration: 1000,
            onClose: () => proxy.$router.go(-1)
        })
    }
    //删除
    const del = async () => {
        proxy.$confirm({
            title: '删除提醒',
            message: '是否确认删除地址',
        }).then(async () => {
            var params = {
                busid: business.id,
                id: addid
            }

            var result = await proxy.$POST({url: 'address/del', params})

            if(result.code == 0)
            {
                proxy.$fail(result.msg)
                return false 
            }
            proxy.$success({
                message: result.msg,
                duration: 1000,
                onClose: () => proxy.$router.go(-1)
            })
        }).catch(() => {
            
        })
    }
</script>